#include <libsoup/soup.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "globals.h"
#include "support.h"

#define LOG_INTERVAL 9
#define NETWORK_TIMEOUT 60
#define LOGSERVER "http://www.tangogps.org"
#define LOGPATH "/demolog.php"

static SoupSession *session = NULL;
static int time_last_update = 0;

SoupSession * 
create_soupsession();

void
send_log();

static void
send_log_cb (SoupSession *session, SoupMessage *msg, gpointer user_data);



void
live_log ()
{
	GList *list;
	GtkWidget *widget;
	trackpoint_t *tp = NULL;
	GString *string;
	const char *nick, *pass;
	char *login;
	static int counter = 0;

	counter++;

	
	if(counter % LOG_INTERVAL != 0)
		return;

	if(!trackpoint_list->length)
		return;

	tp = trackpoint_list->tail->data;
	if(time_last_update >= tp->time)
		return;
	
	
	widget = lookup_widget(window_main, "entry7");
	nick = gtk_entry_get_text(GTK_ENTRY(widget));
	widget = lookup_widget(window_main, "entry8");
	pass = gtk_entry_get_text(GTK_ENTRY(widget));
	
	login = soup_form_encode("nick",nick,"pass",pass,NULL);
	
	string = g_string_new("timestamp=");	
	g_string_append_printf(string, "%d&%s&body=",tp->time,login);

	for(list = trackpoint_list->tail; list != NULL; list = list->prev)
	{
		tp = list->data;
		
		if(tp->time > time_last_update)
			g_string_append_printf(string, "::%d:%f:%f:%.1f:%.1f:%.0f:%.0f:%d%%0A",
					tp->time, tp->lat_deg, tp->lon_deg,
					tp->alt, tp->speed, tp->head, tp->hdop, tp->heart);
	}

	
	send_log(string->str);		
	
	g_string_free(string, FALSE);
	g_free(login);
}


void
send_log(const char *formdata)
{
	SoupMessage *msg;

	msg = soup_message_new ("POST", LOGSERVER LOGPATH);
	soup_message_set_request (	msg, "application/x-www-form-urlencoded",
					SOUP_MEMORY_TAKE,
					formdata, strlen (formdata));
	
	if (!session) session = create_soupsession();
	soup_session_queue_message (session, msg, send_log_cb, NULL);
}


static void
send_log_cb (SoupSession *session, SoupMessage *msg, gpointer user_data)
{
	if (SOUP_STATUS_IS_SUCCESSFUL (msg->status_code))
	{
		time_last_update = atoi(msg->response_body->data);
		printf("updated on: %d %s\n", time_last_update,msg->response_body->data);
	}
	else
		printf("status %d \n", msg->status_code);
	
}



SoupSession * 
create_soupsession() 
{
	SoupSession *session;
	
	session = soup_session_async_new_with_options (
			SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_COOKIE_JAR,
			SOUP_SESSION_USER_AGENT, VERSION ,
			SOUP_SESSION_IDLE_TIMEOUT, NETWORK_TIMEOUT, 
			SOUP_SESSION_TIMEOUT, NETWORK_TIMEOUT,
			NULL);

#if 0
	SoupLogger *logger;
	logger = soup_logger_new (SOUP_LOGGER_LOG_BODY, -1);
	soup_session_add_feature (session, SOUP_SESSION_FEATURE (logger));
	g_object_unref (logger);
#endif
	
	return session;
}
